package com.example.waterdispenserm2.mo.ttldeep;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityDeepSeekBinding;

public class DeepSeekActivity extends BasicsActivity<ActivityDeepSeekBinding> implements InductionCookerProtocolDeep.ProtocolListener{
    private InductionCookerProtocolDeep mProtocol;
    private ImageView[] mLeds = new ImageView[8];

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        // 初始化LED显示
        initLeds();

        // 初始化按键
        initButtons();
// 串口选择逻辑
        binding.btOpen.setOnClickListener(v -> {
            String input = binding.etAdd.getText().toString().trim();
            String path = "/dev/ttyS0"; // 默认路径

            if (!TextUtils.isEmpty(input)) {
                switch (input) {
                    case "0": path = "/dev/ttyS0"; break;
                    case "1": path = "/dev/ttyS1"; break;
                    case "2": path = "/dev/ttyS2"; break;
                    case "3": path = "/dev/ttyS3"; break;
                    case "4": path = "/dev/ttyS4"; break;
                    case "5": path = "/dev/ttyS5"; break;
                    case "6": path = "/dev/ttyS6"; break;
                    case "7": path = "/dev/ttyS7"; break;
                }
            }
            initProtocol(path);
        });

        binding.btClase.setOnClickListener(v->{onDestroy();});
        binding.ivMessage.setOnClickListener(v->{finish();});
    }

    @Override
    protected ActivityDeepSeekBinding getViewBinding() {
        return ActivityDeepSeekBinding.inflate(LayoutInflater.from(this));
    }

    private void initLeds() {
        String[] ledLabels = getResources().getStringArray(R.array.led_labels);

        for (int i = 0; i < mLeds.length; i++) {
            // 创建LED容器
            LinearLayout ledLayout = new LinearLayout(this);
            ledLayout.setOrientation(LinearLayout.VERTICAL);
            ledLayout.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            ));
            ledLayout.setPadding(10, 0, 10, 0);

            // LED指示灯
            ImageView led = new ImageView(this);
            led.setImageResource(R.drawable.led_off);
            led.setLayoutParams(new LinearLayout.LayoutParams(100, 50));
            ledLayout.addView(led);
            mLeds[i] = led;

            // LED标签
            TextView label = new TextView(this);
            label.setText(ledLabels[i]);
            label.setTextSize(12);
            label.setLayoutParams(new LinearLayout.LayoutParams(100, 50));
            label.setGravity(View.TEXT_ALIGNMENT_CENTER);
            ledLayout.addView(label);

            binding.ledContainer.addView(ledLayout);
        }
    }

    private void initButtons() {
        Button btnPower = findViewById(R.id.btnPower);
        Button btnTimer = findViewById(R.id.btnTimer);
        Button btnFunction = findViewById(R.id.btnFunction);
        Button btnDec = findViewById(R.id.btnDec);
        Button btnStart = findViewById(R.id.btnStart);
        Button btnInc = findViewById(R.id.btnInc);

        View.OnClickListener keyListener = v -> {
            byte key = InductionCookerProtocolDeep.KEY_NONE;
            int id = v.getId();

            if (id == R.id.btnPower) {
                key = InductionCookerProtocolDeep.KEY_POWER;
            } else if (id == R.id.btnTimer) {
                key = InductionCookerProtocolDeep.KEY_TIMER;
            } else if (id == R.id.btnFunction) {
                key = InductionCookerProtocolDeep.KEY_FUNCTION;
            } else if (id == R.id.btnDec) {
                key = InductionCookerProtocolDeep.KEY_DEC;
            } else if (id == R.id.btnStart) {
                key = InductionCookerProtocolDeep.KEY_START;
            } else if (id == R.id.btnInc) {
                key = InductionCookerProtocolDeep.KEY_INC;
            }

            if (mProtocol != null && key != InductionCookerProtocolDeep.KEY_NONE) {
                mProtocol.sendKey(key);
            }
        };

        btnPower.setOnClickListener(keyListener);
        btnTimer.setOnClickListener(keyListener);
        btnFunction.setOnClickListener(keyListener);
        btnDec.setOnClickListener(keyListener);
        btnStart.setOnClickListener(keyListener);
        btnInc.setOnClickListener(keyListener);
    }

    private void initProtocol(String device) {
        updateStatus("正在连接: " + device);
        mProtocol = new InductionCookerProtocolDeep(device, 9600);
        mProtocol.start(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProtocol != null) {
            mProtocol.stop();
        }
    }

    @Override
    public void onDisplayUpdate(int digit1, int digit2, int digit3, int digit4, int leds) {
        runOnUiThread(() -> {
            // 更新数码管显示
            binding.tvDigit1.setText(String.valueOf(digit1));
            binding.tvDigit2.setText(String.valueOf(digit2));
            binding.tvDigit3.setText(String.valueOf(digit3));
            binding.tvDigit4.setText(String.valueOf(digit4));

            // 更新LED状态
            for (int i = 0; i < mLeds.length; i++) {
                boolean on = (leds & (0x80 >> i)) != 0;
                mLeds[i].setImageResource(on ? R.drawable.led_on : R.drawable.led_off);
            }
        });
    }

    @Override
    public void onKeySent(byte key) {
        runOnUiThread(() -> updateStatus("按键已发送: " + key));
    }

    @Override
    public void onError(String message) {
        runOnUiThread(() -> updateStatus("错误: " + message));
    }

    @Override
    public void onStatusChanged(boolean connected) {
        runOnUiThread(() -> {
            if (connected) {
                updateStatus("状态: 已连接");
            } else {
                updateStatus("状态: 已断开");
            }
        });
    }

    @Override
    public void onLogMessage(String message) {
        runOnUiThread(() -> {
            binding.tvLog.append(message + "\n");
            // 自动滚动到底部
            int scrollAmount = binding.tvLog.getLayout().getLineTop(binding.tvLog.getLineCount())
                    - binding.tvLog.getHeight();
            if (scrollAmount > 0) {
                binding.tvLog.scrollTo(0, scrollAmount);
            } else {
                binding.tvLog.scrollTo(0, 0);
            }
        });
    }

    private void updateStatus(String message) {
        binding.tvStatus.setText(message);
    }


}